﻿using System;

namespace DotNetCommon.Validate.Annotations;

/// <summary>
/// 字符串必须匹配指定的正则表达式, 示例:
/// <code>
/// [VMustMatchRegex("^1[0-9]{10}$")]
/// public string PhoneNumber { get; set; }
/// </code>
/// </summary>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public sealed class VMustMatchRegexAttribute(string regex, string errorMessage = null) : Attribute, IValidateAction
{
    public string Pattern { get; set; } = regex;
    public string ErrorMessage { get; set; } = errorMessage;

    public void Action(IValidateContext ctx)
    {
        ValidateStringExtensions.MustMatchRegexInternal(ctx, ctx.ModelValue?.ToString(), Pattern, ErrorMessage);
    }
}

/// <summary>
/// 如果不为null, 则字符串必须匹配指定的正则表达式, 示例:
/// <code>
/// [VMustMatchRegexIfNotNull("^1[0-9]{10}$")]
/// public string PhoneNumber { get; set; }
/// </code>
/// </summary>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public sealed class VMustMatchRegexIfNotNullAttribute(string regex, string errorMessage = null) : Attribute, IValidateAction
{
    public string Pattern { get; set; } = regex;
    public string ErrorMessage { get; set; } = errorMessage;

    public void Action(IValidateContext ctx)
    {
        if (ctx.ModelValue == null) return;
        ValidateStringExtensions.MustMatchRegexInternal(ctx, ctx.ModelValue?.ToString(), Pattern, ErrorMessage);
    }
}
